<template>
    <div class="login-container">
        <div class="login-wrap">
            <div class="logo-wrap">
                <van-image 
                    class="logo-image"
                    round
                    :src="logo" 
                    fit="contain" 
                />
                <span class="title">E点点</span>
            </div>

            <van-form @submit="onSubmit" @failed="onFailed" :show-error="false">
                <div class="telephone">
                    <van-field
                        class="loginInput"
                        name="telephone"
                        v-model="user.telephone"
                        placeholder="输入手机号"
                        :rules="[{pattern: telePattern, message: '手机号码不合法' }]"
                    >
                    <van-icon class="iconfont" class-prefix="icon" slot="left-icon" name="shoujihao"></van-icon>
                    </van-field>
                </div>

                <div class="password">
                    <van-field
                        class="loginInput"
                        name="password"
                        type="password"
                        v-model="user.password"
                        placeholder="输入密码"
                        :rules="[{pattern: passwordPattern, message: '密码必须以字母开头，长度在6~18之间，只能包含字母、数字和下划线' }]"
                    >
                    <van-icon class="iconfont" class-prefix="icon" slot="left-icon" name="mima"></van-icon>
                    </van-field>
                </div>
                
                <div class="register">
                    <span class="registerBtn" @click="toRegister">新用户点击注册</span>
                </div>

                <div class="submit">
                    <van-button class="subBtn" round color="rgb(247,147,30)" native-type="submit"><span class="sub">登录</span></van-button>
                </div>
            </van-form>

        </div>
    </div>
</template>

<script>
import {login} from '@/api/user'
import { mapMutations } from 'vuex';

export default {
    name: 'Login',

    data() {
        return {
            logo:require('@/assets/images/Ediandian.png'),
            user:{
                telephone:'',
                password:''
            },
            telePattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            passwordPattern:/^[a-zA-Z]\w{5,17}$/
        
        }; 
    },

    mounted() {
        
    },

    methods: {
        ...mapMutations('user',{setUser:'setUser'}),
        /**
         * 表单校验无误后的处理
         */
        onSubmit() { 
            //这是之前的对象复制写法 
            // let user = {...this.user}
            // 2023-01-18修改 
            let user = JSON.parse(JSON.stringify(this.user))

            this.$toast.loading({
                message: '登录中...',
                forbidClick: true,
            }) 
            login(user).then(res => {
                /*2023-01-18：这里给出修改意见  --2023-2-10补充，更进一步将业务代码与其他处理状态的代码分离
                 * 设置正在加载状态
                 *login.then(res=>{ 
                 *   if(!res.自定义状态码){ 
                 *       //自定义状态码处理业务错误
                 *       message(状态码信息，即错误原因，账号密码错误或其他)
                 *   }
                 *   //后续登录业务
                 * })
                 *  .catch(err =>{ 
                 *      //这里处于其他错误，如：请求发送成功但服务器响应出错，请求发送成功但未收到响应，请求发送失败等
                 *   })
                 *  .finally { 
                 *     这里设置加载完成
                 *  }
                 * 
                 */
                /**
                 * 2023-2-10 参考https://www.axios-http.cn/docs/handling_errors
                 * axios.get('/user/12345')
                 *  .catch(function (error) {
                 *    if (error.response) {
                 *       // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
                 *       console.log(error.response.data);
                 *        console.log(error.response.status);
                 *        console.log(error.response.headers);
                 *        } else if (error.request) {
                 *        // 请求已经成功发起，但没有收到响应
                 *        // `error.request` 在浏览器中是 XMLHttpRequest 的实例，
                 *        // 而在node.js中是 http.ClientRequest 的实例
                 *        console.log(error.request);
                 *        } else {
                 *        // 发送请求时出了点问题
                 *        console.log('Error', error.message);
                 *        }
                 *        console.log(error.config);
                 *    });
                 **/
                let result = JSON.stringify(res.data)
                window.localStorage.setItem("result",result)
                this.setUser(res.data.user)
                this.$toast.success('登录成功')
                setTimeout(() => {
                    this.$toast.clear()
                    this.$router.push({ 
                        name:'home'
                    })
                }, 500);
            }).catch(err => { 
                let status = err.response.status

                if(status === 400) { 
                     this.$toast.fail("手机号码或用户名错误")
                }
            }) 
        },
         
        /**
         * 表单校验失败的处理
         */
        onFailed(err) {
            if(err.errors[0]){ 
                let errMsg = err.errors[0].message
                this.$dialog.alert({ 
                    title:'提示',
                    message:errMsg
                })
            }
            
        },

        /**
         * 点击注册
         */
        toRegister(){ 
            this.$router.push({ 
                name:'register'
            })
        }
    },
};
</script>

<style scoped>
.login-container{ 
    width: 100%;
    height: 100%;
    display: flex;
    background-image: url('~@/assets/images/loginBack.png');
    background-size: cover;
    background-repeat: no-repeat;
}

.login-wrap{ 
    width: 350px;
    height: 390px;
    margin: 75px auto;
}

/**logo区 */
.logo-wrap{ 
    width: 120px;
    height: 150px;
    margin: auto;
}

.logo-wrap .title {
    display: block; 
    width: 100px;
    font-size: 24px;
    color: #ffffff;
    text-align: center;
    padding-left: 20px;
    letter-spacing: 5px;
}

/**logo图片 */
.logo-wrap .logo-image { 
    width: 120px;
    height: 120px;
}

.telephone,.password{ 
    width: 300px;
    height: 40px;
    margin: 30px auto;
    border-radius: 40px;
    overflow: hidden;
}

.password { 
    margin-bottom: 10px;
}

.loginInput{ 
    background-color: rgba(255,255,255,.4) !important;
}

.register{ 
    width: 300px;
    margin: auto;
}

.registerBtn{ 
    display: block;
    width: 100%;
    color: rgb(251,176,59);
    font-size: 15px;
    text-align: right;
    cursor: pointer;
}

.submit { 
    width: 100px;
    height: 30px;
    margin: 30px auto;
}

.subBtn{ 
    width: inherit;
}

.sub{ 
    font-size: 18px;
    letter-spacing: 5px;
}
</style>